package cn.webrx;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-06-05 14:36
 */
@Slf4j
public class Demo {
    public static void main(String[] args) {
        DefaultSecurityManager sm = new DefaultSecurityManager();
        IniRealm inirealm = new IniRealm("classpath:shiro.ini");
        sm.setRealm(inirealm);
        SecurityUtils.setSecurityManager(sm);
        Subject su = SecurityUtils.getSubject();
        String user = "zhangsan";
        String pass = "123";
        UsernamePasswordToken token = new UsernamePasswordToken(user, pass);
        try {
            su.login(token);//身份验证码
            if (su.isAuthenticated()) {
                if (su.hasRole("admin")) {
                    System.out.println("是管理员");
                    log.debug("是管理员");

                } else {
                    System.out.println("不是管理员");
                }

                if (su.isPermitted("user:add")) {
                    System.out.println("有用户 usre:add权限");
                }
            }
        } catch (UnknownAccountException uae) {
            System.out.println(String.format("账号名:%s，不存在.", user));
        } catch (IncorrectCredentialsException ice) {
            System.out.println("密码错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
